﻿using FastCloud.Base.Config;
using FastCloud.Base.Desgin;
using FastCloud.Base.Entity;
using FastCloud.DMP.Entity;
using FastIOC.Attribute;
using FastORM.Entity;
using FastUtil.Convert;
using FastUtil.Data;
using System;
using System.Collections.Generic;
using System.Text;

namespace FastCloud.DMP.DB
{
    public class DB_Table : BaseDBML<Frame_Table>
    {
        [AutoWired]
        private DB_Project DB_Project;

        public override void Insert(Frame_Table Entity)
        {
            if (string.IsNullOrEmpty(Entity.TableGuid))
            {
                Entity.TableGuid = GenerateUtil.GenerateUnitGuid();
            }
            string BaseCode = "";
            if (Entity.ProjectGuid != "Top")
            {
                Frame_Project ProjectEntity = DB_Project.SelectOne(Entity.ProjectGuid);
                BaseCode = ProjectEntity.ProjectCode;
            }
            List<ParamEntity> ParamList = new List<ParamEntity>() { new ParamEntity() { ParamName = "ProjectGuid", ParamValue = Entity.ProjectGuid } };
            string MaxCode = DTO.ExecuteToString("select max(TableCode) from Frame_Table where ProjectGuid=@ProjectGuid", ParamList);
            string TableCode = "";
            if (string.IsNullOrEmpty(MaxCode))
            {
                TableCode = BaseCode + "1000";
            }
            else
            {
                MaxCode = MaxCode.Substring(BaseCode.Length, MaxCode.Length - BaseCode.Length);
                TableCode = BaseCode + (ValueConvert.ConvertToInt32(MaxCode) + 1);
            }
            Entity.TableCode = TableCode;
            Entity.AddDate = DateTime.Now;
            base.Insert(Entity);
          
        }

        public override void DeleteByID(string UnitGuid)
        {
            //删除表
            Frame_Table Entity = SelectOne(UnitGuid);
            string DDLSQL = string.Format("DROP Table  IF EXISTS {0}", Entity.TablePhysicalName);
            DTO.ExecuteSQL(DDLSQL);
            base.DeleteByID(UnitGuid);
        }

        public bool ExistTable(string TablePhysicalName)
        {
            List<ParamEntity> ParamList = new List<ParamEntity>() { new ParamEntity() { ParamName = "TablePhysicalName", ParamValue = TablePhysicalName } };
            string sql = "TablePhysicalName=@TablePhysicalName";
            return SelectCount(sql, ParamList) > 0;
        }

    }
}
